package com.hmall.item.controller;

import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.TbItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private TbItemService tbItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品数据
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> searchItemByPage(@RequestParam("page") Long page, @RequestParam("size") Long size) {
        PageDTO<Item> result = tbItemService.searchItemByPage(page, size);
        return result;
    }

    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item searchItemById(@PathVariable Long id) {
        return tbItemService.getById(id);
    }

    /**
     * 新增商品
     *
     * @param item
     */
    @PostMapping
    public void saveItem(@RequestBody Item item) {
        item.setCreateTime(new Date(System.currentTimeMillis()));
        tbItemService.save(item);
        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_INSERT_UPDATE_KEY,item.getId());
    }

    /**
     * 商品上架、下架
     * id：商品id，status：商品状态 1-代表上架 2-代表下架
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateStatusById(@PathVariable Long id,
                                 @PathVariable Integer status) {
        tbItemService.updateStatusById(id, status);
        if (status == 1) {
            rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_INSERT_UPDATE_KEY,id);
        } else if (status == 2) {
            rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_DELETE_KEY,id);
        }
    }

    /**
     * 修改商品
     *
     * @param item
     */
    @PutMapping
    public void updateItem(@RequestBody Item item) {
        item.setUpdateTime(new Date(System.currentTimeMillis()));
        tbItemService.updateById(item);
    }

    /**
     * 根据id删除商品
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        tbItemService.removeById(id);
    }
}

